<template>
  <div>
    <van-nav-bar
      title="登录"
      left-text="返回"
    />

    <van-tabs v-model="active">
      <van-tab title="手机登录">
        <van-form ref="mobileForm" @submit="onSubmitMobile">
          <van-field
            v-model="mobileForm.phone"
            name="phone"
            label="手机号"
            placeholder="请输入手机号"
            :rules="mobileFormRules.phone"
          />
          <van-field
            v-model="mobileForm.password"
            type="password"
            name="密码"
            label="密码"
            placeholder="请输入四位验证码"
            :rules="[{ required: true, message: '请填写密码' }]"
          >
          </van-field>
          <div style="margin: 16px;">
            <van-button color="linear-gradient(to right, #ff6034, #ee0a24)" round block native-type="submit">登录</van-button>
          </div>
        </van-form>
      </van-tab>
      <van-tab title="邮箱登录">邮箱登录</van-tab>
    </van-tabs>

    <router-link class="goReg" to="/reg">去注册</router-link>
  </div>
</template>

<script>
import { login } from '@/api/login.js'
import { Toast } from 'vant'
export default {
  data () {
    return {
      active: 'mobile',
      mobileForm: {
        phone: '',
        password: ''
      },
      mobileFormRules: {
        phone: [
          { required: true, message: '请填写手机号' },
          {
            validator: (val, rule, callback) => {
              const reg = /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/
              if (reg.test(val)) {
                return true
              } else {
                return false
              }
            },
            message: '手机号码格式不正确'
          }
        ]
      }
    }
  },

  created () {

  },

  methods: {
    async onSubmitMobile () {
      const res = await login(this.mobileForm)
      console.log(res)
      if (res.data.code !== 200) {
        return Toast('手机号或密码错误')
      }
      Toast.success('登录成功')
      localStorage.setItem('wyy-token', res.data.token)
      this.$router.push('/user')
    }
  }
}
</script>

<style scoped lang='less'>
.goReg {
  text-align: center;
  display: inline-block;
  width: 100%;
  font-size: 14px;
  color: #ee0a24;
}
</style>
